package com.example.zwh.computershop.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zwh.computershop.Home_Activity;
import com.example.zwh.computershop.Myapp;
import com.example.zwh.computershop.R;
import com.example.zwh.computershop.androidUtil.ActivityCollector;
import com.example.zwh.computershop.handleDataClient.handleData;
import com.example.zwh.computershop.sqlModel.Cart;
import com.example.zwh.computershop.sqlModel.Order;
import com.example.zwh.computershop.sqlModel.User;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class Login extends AppCompatActivity implements View.OnClickListener {

    Intent intent;
    Toast toast;
    TextView register_skip;
    Button btn_login;
    EditText login_em;
    EditText login_pwd;


    int state = -1;
    String psw;
    String em;
    User user;
    Myapp myapp;

    private LinearLayout accountLayout, pwdLayout;
    private ImageView accountImage, pwdIamge, loginBack;

    public static final String REGEX_EMAIL = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    String accountString;
    //private int auto = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        ActivityCollector.addActivity(this);
        initView();
        //autoLogin();
        initEvent();
    }
//存了信息就提取自动登录
//    public void autoLogin() {
//        File file = new File("content.WebInfo");
//        if(!file.exists()) return;
//        AutoUser auser = null;
//        try {
//            FileInputStream fis = new FileInputStream(file);
//            ObjectInputStream ois = new ObjectInputStream(fis);
//            Object obj = null;
//            try {
//                auser = (AutoUser) ois.readObject();
//                ois.close();
//                fis.close();
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        auto = 0;
//        em = auser.getEmail();
//        psw = auser.getPassword();
//        Login(user);
//    }

    public void initView() {
        //获取个存登录的单列类
        myapp = (Myapp) getApplication();
        register_skip = (TextView) findViewById(R.id.register_skip);
        btn_login = (Button) findViewById(R.id.btn_login);
        login_em = (EditText) findViewById(R.id.em);
        login_pwd = (EditText) findViewById(R.id.pwd);
        user = new User();
        login_em.setText("zwhzsjwx@163.com");
//        login_pwd.setText("123456");

        accountLayout = findViewById(R.id.login_name);
        pwdLayout = findViewById(R.id.login_pwd);
        accountImage = findViewById(R.id.iv_login_name);
        pwdIamge = findViewById(R.id.iv_login_pwd);
        loginBack = findViewById(R.id.login_back);
    }

    public void initEvent() {
        register_skip.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        loginBack.setOnClickListener(this);

        login_em.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    setNoSelected();
                    accountLayout.setSelected(true);
                    accountImage.setSelected(true);
                }
            }

        });

        login_pwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                setNoSelected();
                pwdLayout.setSelected(true);
                pwdIamge.setSelected(true);
            }
        });

        login_em.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                inputIsOK();
            }
        });
        login_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                inputIsOK();
            }
        });

        btn_login.setEnabled(false);

    }

    //判断输入是否合法，合法则登录按钮可用。
    private void inputIsOK() {
        accountString = login_em.getText().toString().trim();
        String passwordString = login_pwd.getText().toString().trim();
        if (accountString.length() > 5 && passwordString.length() > 5) {
            btn_login.setEnabled(true);
            btn_login.setBackgroundResource(R.drawable.login_actived);
            return;
        }
        btn_login.setEnabled(false);
        btn_login.setBackgroundResource(R.drawable.login_common);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                Login(user);
                //user.printInfo();
                System.out.println("***" + state);

                if (state == 2) {
                    //user.printInfo();
                    toast.makeText(Login.this, "登录成功", Toast.LENGTH_SHORT).show();
                    //登录成功
                    myapp.setUser(user);
                    myapp.setLoState(1);
                    intent = new Intent(Login.this, Home_Activity.class);
                    startActivity(intent);
                    finish();
                }
//                } else if (state == -1) {
//                    toast.makeText(Login.this, "不能为空", Toast.LENGTH_SHORT).show();
//                }
                else if (state == 1) {
                    toast.makeText(Login.this, "账户不存在", Toast.LENGTH_SHORT).show();
                } else if (state == 3) {
                    toast.makeText(Login.this, "密码错误", Toast.LENGTH_SHORT).show();
                } else if (state == 5) {
                    toast.makeText(Login.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.register_skip:
                // toast.makeText(Login.this, "注册", Toast.LENGTH_SHORT).show();
                intent = new Intent(Login.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.login_back:
                finish();
                intent = new Intent(this, Home_Activity.class);
                startActivity(intent);
                break;
        }
    }

    void setNoSelected() {
        accountLayout.setSelected(false);
        accountImage.setSelected(false);
        pwdLayout.setSelected(false);
        pwdIamge.setSelected(false);
    }

    public void Login(User user) {
        //if (auto == 1) {

        em = login_em.getText().toString();
        psw = login_pwd.getText().toString();

        if (!Pattern.matches(REGEX_EMAIL, accountString)){
            System.out.print("请输入正确邮箱哦");
            Toast.makeText(this, "请输入正确邮箱哦", Toast.LENGTH_SHORT).show();
            return;
        }
        Thread t = new Thread(new takeThread());
        t.start();
        try {
            t.join();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
//        }else {
//            Thread t = new Thread(new takeThread());
//            t.start();
//            try {
//                t.join();
//            }catch (InterruptedException ie) {
//                ie.printStackTrace();
//            }
//            myapp.setUser(user);
//            myapp.setLoState(1);
//            intent = new Intent(Login.this, Home_Activity.class);
//            startActivity(intent);
//            finish();
//        }
    }

    class takeThread extends Thread {
        @Override
        public void run() {
            state = handleData.handleLogin(em, psw, user);
            if (state == 2) {
                ArrayList<Cart> cat = new ArrayList<>();

                int state2 = handleData.getCart(cat, user.getId());
                if (state2 == 3) {
                    myapp.setCart(cat);
                }

                ArrayList<Order> ord = new ArrayList<>();
                state2 = handleData.getOrd(ord, user.getId());
                if (state2 == 3) {
                    myapp.setOra(ord);
                }

            }
            user.printInfo();
        }
    }
//保存用户信息
//    public static void saveUser(AutoUser autoUser) {
//        try {
//            File file = new File("content.WebInfo");
//            if(!file.exists()) {
//                try {
//                    file.createNewFile();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            FileOutputStream fos = new FileOutputStream(file);
//            ObjectOutputStream oos = new ObjectOutputStream(fos);
//            oos.writeObject(autoUser);
//            oos.close();
//            fos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
